package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.BusinessDispatchOrderDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.SysUtil;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-02-07
 */
@Service
@Transactional
public class BusinessDispatchOrderServiceImpl extends ServiceImpl<BusinessDispatchOrderDao, BusinessDispatchOrder> implements BusinessDispatchOrderService {
    @Resource
    private BusinessOrderService orderService;
    @Resource
    private CarService carService;
    @Resource
    private RegionService regionService;
    @Resource
    private CarFleetService carFleetService;
    @Resource
    private BusinessDocumentService businessDocumentService;
    @Resource
    private ContractService contractService;
    @Resource
    private ComsumerService comsumerService;

    @Resource
    private ImgService imgService;

    @Resource
    TypeDicService typeDicService;
    @Resource
    private CarLogService carLogService;
    @Resource
    private HttpServletRequest request;
    @Override
    public Map<String, Object> getAll(BusinessDispatchOrder dispatchOrder, InputParam inputParam) {
        QueryWrapper<BusinessDispatchOrder> ew=new QueryWrapper<>();

//        if(!StringUtils.isEmpty(inputParam.getName())){
//            //根据合同名称查询
//            ew.inSql("business_document_id","select id from business_document where contract_id in(select id from contract where project like '%"+inputParam.getName()+"%' )");
//        }
        if(!StringUtils.isEmpty(inputParam.getLicencePlate())){
            //根据车牌
//            ew.inSql("business_document_id","select id from business_document where contract_id in(select id from contract where contract_type = '"+inputParam.getContractType()+"' )");
            ew.inSql("car_id","select id from car where licence_plate like '%"+inputParam.getLicencePlate()+"%'");
        }
        //查询订单
        if(!StringUtils.isEmpty(dispatchOrder.getOrderId())){
            //根据车队查询
            ew.eq("order_id",dispatchOrder.getOrderId());
        }
        if(dispatchOrder.getState()!=null){
            //根据状态查询
            ew.eq("state",dispatchOrder.getState());
        }
        if(dispatchOrder.getSatchelFlag()!=null){
            //根据是否填写过磅单的状态查询
            if(dispatchOrder.getSatchelFlag().equals(0)){
                ew.isNull("satchel_flag");
            }else {
                ew.eq("satchel_flag", dispatchOrder.getSatchelFlag());
            }
        }
        //磅单录入用到，完成时间传入字段dateStr
        if(!StringUtils.isEmpty(inputParam.getDateStr())){
            ew.between("complete_time",inputParam.getDateStr()+" 00:00:00",inputParam.getDateStr()+" 23:59:59");
        }
        ew.orderByDesc("create_time");
        Page<BusinessDispatchOrder> result = this.page(new Page<BusinessDispatchOrder>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BusinessDispatchOrder> rows=result.getRecords();
        for (int i = 0; i < rows.size(); i++) {
            BusinessDispatchOrder temp = getOtherInfo(rows.get(i));
            rows.set(i,temp);
        }
        map.put("rows", rows);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }
    @Override
    public BusinessDispatchOrder getOtherInfo(BusinessDispatchOrder temp){
        //车辆信息
        Car car=carService.getById(temp.getCarId());
        temp.setCar(car);
        //获取订单
        BusinessOrder order=orderService.getById(temp.getOrderId());
        //获取定位信息
        //特殊处理，原本的区域不使用，改成读取字典数据
//            Region startRegion=regionService.getById(order.getStartPlace());
//            Region endRegion=regionService.getById(order.getEndPlace());
        Region startRegion = typeDicService.formatRegion(order.getStartPlace());
        Region endRegion = typeDicService.formatRegion(order.getEndPlace());
        order.setStartRegion(startRegion);
        order.setEndRegion(endRegion);
        temp.setBusinessOrder(order);
        return temp;
    }

    @Override
    public Map<String, Object> add(String orderId, String carDataJson) {
        BusinessOrder order=orderService.getById(orderId);
        if (order==null){
            return ResponseInfo.error("错误的参数");
        }
        if (order.getState()!=BusinessOrder.STATUS_CREATE){
            return ResponseInfo.error("订单已派单或已完成");
        }
        //将json数据转换成容器对象
        List<Map<String,Object>> data= (List<Map<String, Object>>) JSON.parse(carDataJson);
        BigDecimal total=new BigDecimal(0);
        List<BusinessDispatchOrder> list=new ArrayList<>();
        for (int i = 0; i <data.size() ; i++) {
            BigDecimal num=new BigDecimal((String) data.get(i).get("num"));//数量
            total=total.add(num);
            Car car=carService.getById((String) data.get(i).get("id"));//车辆id
            if (car==null){
                return ResponseInfo.error("错误的车辆");
            }
            if (car.getState()!=Car.STATE_FREE){
                return ResponseInfo.error("错误的车辆状态");
            }
//            if (num.compareTo(car.getLoadCapacity())>=1){//分配重量必须小于最大载重
//                return ResponseInfo.error("错误的数量");
//            }
            BusinessDispatchOrder dispatchOrder=new BusinessDispatchOrder();
            dispatchOrder.setId(SysUtil.UUID());
            dispatchOrder.setOrderId(orderId);
            dispatchOrder.setCarId(car.getId());
            car.setState(Car.STATE_WORK);//设置车辆状态为占用
            dispatchOrder.setCar(car);//用于修改车辆状态
            dispatchOrder.setNum(num);
            dispatchOrder.setState(BusinessDispatchOrder.STATUS_CREATE);
            dispatchOrder.setRemark((String) data.get(i).get("remark"));
            dispatchOrder.setCreateTime(LocalDateTime.now());
            list.add(dispatchOrder);
        }

        if (total.compareTo(order.getLastNum())!=0){
            return ResponseInfo.error("单据分配数据错误");
        }
        for (int i = 0; i <list.size() ; i++) {
            BusinessDispatchOrder dispatchOrder=list.get(i);
            carService.updateById(dispatchOrder.getCar());//更新车辆状态
            this.save(dispatchOrder);//插入派单信息
        }
        //设置订单完成中
        order.setState(BusinessOrder.STATUS_WORKED);
        order.setLastNum(order.getLastNum().subtract(total));//剩余数量减去当前分配数量
        orderService.updateById(order);
        return ResponseInfo.success();
    }

    /**
     * 取消订单
     * @param id
     * @return
     * 取消派单，并修改订单状态与剩余数量
     */
    @Override
    public Map<String, Object> dele(String id,String reason) {
        BusinessDispatchOrder dispatchOrder=this.getById(id);
        if (dispatchOrder==null){
            return ResponseInfo.error("错误参数");
        }
        if (dispatchOrder.getState()!=BusinessDispatchOrder.STATUS_CREATE){
            return ResponseInfo.error("只有未完成订单可以删除");
        }
        this.removeById(id);
//        修改订单状态与剩余数量
        BusinessOrder order=orderService.getById(dispatchOrder.getOrderId());
        order.setState(BusinessOrder.STATUS_CREATE);
        order.setLastNum(order.getLastNum().add(dispatchOrder.getNum()));
        orderService.updateById(order);
        //解除车辆占用
        Car car=carService.getById(dispatchOrder.getCarId());
        if (car.getState().equals(Car.STATE_WORK)){
            car.setState(Car.STATE_FREE);
            carService.updateById(car);
        }
        //添加车辆异常日志
        carLogService.add(dispatchOrder.getCarId(),CarLog.car_back,reason,SysUtil.getLoginUserId(request));
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> changeState(String id, Integer state) {
        BusinessDispatchOrder dispatchOrder=this.getById(id);
        LocalDateTime completeTime=null;
        if (dispatchOrder==null||SysUtil.BUSINESS_DISPATCH_ORDER_STATE_MAP.get(state)==null){
            return ResponseInfo.error("错误参数");
        }
        if (state==BusinessDispatchOrder.STATUS_CREATE){//如果状态改为待完成
            dispatchOrder.setCompleteTime(null);
        }else{
            completeTime=LocalDateTime.now();
            dispatchOrder.setCompleteTime(completeTime);
        }
        dispatchOrder.setState(state);
        //更新订单
        UpdateWrapper<BusinessDispatchOrder> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("state",dispatchOrder.getState());
        updateWrapper.set("complete_time",dispatchOrder.getCompleteTime());
        updateWrapper.eq("id",dispatchOrder.getId());
        this.update(updateWrapper);
        //根据不同状态切换车辆状态
        Car car=carService.getById(dispatchOrder.getCarId());
        if (car.getState()!=Car.STATE_ERROR){//车辆状态如果异常，不允许修改
            if (state==BusinessDispatchOrder.STATUS_CREATE){//如果状态改为待完成
                car.setState(Car.STATE_WORK);
            }else{
                car.setState(Car.STATE_FREE);
            }
            carService.updateById(car);
        }
        if (completeTime!=null){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String timeStr = formatter.format(completeTime);
            return ResponseInfo.success(timeStr);
        }
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> updateRemark(String id, String remark) {
        BusinessDispatchOrder dispatchOrder=this.getById(id);
        if (dispatchOrder==null){
            return ResponseInfo.error("错误参数");
        }
        dispatchOrder.setRemark(remark);
        this.updateById(dispatchOrder);
        return ResponseInfo.success();
    }

    /**
     * 更改订单车辆
     * @param id
     * @param carId
     * @return
     */
    @Override
    public Map<String, Object> changeCar(String id, String carId,String reason) {
        BusinessDispatchOrder dispatchOrder=this.getById(id);
        if (dispatchOrder==null){
            return ResponseInfo.error("错误参数");
        }
        Car new_car=carService.getById(carId);//新车辆
        Car old_car=carService.getById(dispatchOrder.getCarId());//新车辆
        //新车辆不可为空，必须为空闲
        if (new_car==null|| !new_car.getState().equals(Car.STATE_FREE)){
            return ResponseInfo.error("车辆不可为空，必须为空闲");
        }else{
            new_car.setState(Car.STATE_WORK);
        }
        //如果车辆状态是异常，则不可改变,否则旧车状态改为空闲
//        if (!old_car.getState().equals(Car.STATE_ERROR)){
//            old_car.setState(Car.STATE_FREE);
//        }
        //原有车辆强制异常
        old_car.setState(Car.STATE_ERROR);
        //更新车辆与订单状态
        carService.updateById(old_car);
        carService.updateById(new_car);
        dispatchOrder.setCarId(carId);
        this.updateById(dispatchOrder);
        //添加车辆异常日志
        carLogService.add(old_car.getId(),CarLog.car_error,reason,SysUtil.getLoginUserId(request));
        //返回新车辆数据
        return ResponseInfo.success(new_car);
    }

    @Override
    public Map<String, Object> detail(String id) {
        BusinessDispatchOrder dispatchOrder=this.getById(id);
        if (dispatchOrder==null){
            return ResponseInfo.error("错误参数");
        }
        //车辆信息
        Car car=carService.getById(dispatchOrder.getCarId());
        dispatchOrder.setCar(car);
        //获取订单
        BusinessOrder order=orderService.getById(dispatchOrder.getOrderId());
        dispatchOrder.setBusinessOrder(order);
        //关联的订单信息
        BusinessDocument document=businessDocumentService.getById(order.getBusinessDocumentId());
        order.setBusinessDocument(document);
        if (document!=null){//订单本身的合同与客户信息
            Contract contract=contractService.getById(document.getContractId());
            document.setContract(contract);
            Comsumer comsumer=comsumerService.getById(document.getCustomerId());
            document.setComsumer(comsumer);
        }
        //车队信息
        CarFleet carFleet=carFleetService.getById(order.getCarfleetId());
        order.setCarFleet(carFleet);
        //获取定位信息
        //特殊处理，原本的区域不使用，改成读取字典数据
//            Region startRegion=regionService.getById(order.getStartPlace());
//            Region endRegion=regionService.getById(order.getEndPlace());
        Region startRegion = typeDicService.formatRegion(order.getStartPlace());
        Region endRegion = typeDicService.formatRegion(order.getEndPlace());
        order.setStartRegion(startRegion);
        order.setEndRegion(endRegion);
        return ResponseInfo.success(dispatchOrder);
    }

    @Override
    public Map<String, Object> getByOrderId(InputParam inputParam) {
        QueryWrapper<BusinessDispatchOrder> ew=new QueryWrapper<>();
        if(StringUtils.isEmpty(inputParam.getMainId())){
            return ResponseInfo.error("参数错误");
        }
        ew.eq("order_id",inputParam.getMainId());
        ew.orderByDesc("create_time");
        Page<BusinessDispatchOrder> result = this.page(new Page<BusinessDispatchOrder>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BusinessDispatchOrder> rows=result.getRecords();
        for (int i = 0; i < rows.size(); i++) {
            BusinessDispatchOrder temp=rows.get(i);
            //车辆信息
            Car car=carService.getById(temp.getCarId());
            temp.setCar(car);
            //获取订单
//            BusinessOrder order=orderService.getById(temp.getOrderId());
//            temp.setBusinessOrder(order);
            //获取定位信息
//            Region startRegion=regionService.getById(order.getStartPlace());
//            Region endRegion=regionService.getById(order.getEndPlace());
//            order.setStartRegion(startRegion);
//            order.setEndRegion(endRegion);
        }
        map.put("rows", rows);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> satchelEdit(String deleIdStr, MultipartFile[] voucherFilesList, BusinessDispatchOrder dispatchOrder, InputParam inputParam) {
        dispatchOrder.setSatchelFlag(1);
        this.updateById(dispatchOrder);
        //驾驶证有图片则保存图片
        if(voucherFilesList.length>0){
            imgService.upload( SysUtil.STACHEL,dispatchOrder.getId(),voucherFilesList);
        }
        //删除图片
        if(!StringUtils.isEmpty(deleIdStr)){
            String[] deleIdArr = deleIdStr.split(",");
            if(deleIdArr.length>0){
                for (String id : deleIdArr) {
                    imgService.deleById(id);
                }
            }
        }
        return ResponseInfo.success(dispatchOrder);
    }
}
